package com.sgb.kjwl.viewmodel.home;

import android.content.Intent;

import androidx.databinding.ObservableField;

import com.google.gson.reflect.TypeToken;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.HomeMenuEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson3;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.AreaChooseEntity;
import com.sgb.kjwl.model.entity.user.ConcreteEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.model.entity.user.MaterChooseEntity;
import com.sgb.kjwl.model.entity.user.RecommendListEntity;
import com.sgb.kjwl.model.entity.user.TwoOrThreeLevelEntity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.MaterialRepertory;
import com.sgb.kjwl.view.ui.fragment.home.GoodsMainGoodsListFragment3;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.view.entity.MenuEntity;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;

/**
 * @author qiangheNoooo
 * * 说明：商品首页（商品、自营、促销）
 * * 时间：2021.07.02
 */
public class GoodsMainGoodsListModel3 extends BaseViewModel {
    public ObservableField<MaterialFilterJson3> materialFilterJson = new ObservableField<>(new MaterialFilterJson3());
    public ObservableField<String> areaCode = new ObservableField<>("");
    private final GoodsMainGoodsListFragment3 mFragment;
    private final MaterialRepertory mRepertory;

    public GoodsMainGoodsListModel3(GoodsMainGoodsListFragment3 fragment, MaterialRepertory repertory) {
        this.mFragment = fragment;
        this.mRepertory = repertory;
    }

    public void getFilterBrandModel(String id,boolean isPopWindow) {
        NewAPIManager.getInstance().getMaterialAPI().getBrandChoose(mRepertory.getAreaCode(), id).enqueue(new Callback<BaseEntity<List<DictEntity3>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<DictEntity3>>> call, @NotNull Response<BaseEntity<List<DictEntity3>>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.showBrandPopWindow(response.body().getData(),isPopWindow);
                } else {
                    MToast.showToast(mFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<DictEntity3>>> call, @NotNull Throwable t) {
                MToast.showToast(mFragment.getActivity(), t.getMessage());
            }
        });
    }

    public void getMaterialBrand(String id) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("areaCode", mRepertory.getAreaCode());
        map.put("id", id);
        APIManager.getInstance().getGoodsAPI().getMaterChoose(map).enqueue(new Callback<BaseEntity<List<MaterChooseEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<MaterChooseEntity>>> call, @NotNull Response<BaseEntity<List<MaterChooseEntity>>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<MaterChooseEntity> list = response.body().getData();
                    for (MaterChooseEntity materChooseEntity : list) {
                        materChooseEntity.getType().add(0, new MaterChooseEntity.TypeBean("全部", ""));
                    }
                    mFragment.setMaterialBrandData(list);
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<MaterChooseEntity>>> call, @NotNull Throwable t) {
            }
        });
    }

    public void getFilterDistance(String cid1,boolean isPopWindow) {
        DialogHelper.showProgressDialog(mFragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getGoodsMaterialDistanceData(cid1).enqueue(new Callback<BaseEntity<List<DictEntity3>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<DictEntity3>>> call, @NotNull Response<BaseEntity<List<DictEntity3>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.setDistanceData(response.body().getData(),isPopWindow);
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<DictEntity3>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getAreaData(boolean isRegionalConnection) {
        Type type = new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.AREA_JSON, type);
        if (obj != null) {
            List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> dataList = (List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>) obj;
            if (isRegionalConnection) {
                mFragment.setAddressData(dataList, mRepertory.getAreaCode());
            } else {
                mFragment.setAddressData(dataList, "");
            }
        } else {
            APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
                @Override
                public void onResponse(@NotNull Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, @NotNull Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                    if (response.body() == null) {
                        return;
                    }
                    if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                        if (isRegionalConnection) {
                            mFragment.setAddressData(response.body().getData(), mRepertory.getAreaCode());
                        } else {
                            mFragment.setAddressData(response.body().getData(), "");
                        }
                    } else {
                        MToast.showToast(mFragment.getContext(), response.body().getMsg());
                    }
                }

                @Override
                public void onFailure(@NotNull Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, @NotNull Throwable t) {
                }
            });
        }
    }

    public void goLogin() {
        int type = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, true);
        if (type == ACAdminDialogUtils.TYPE_NORMAL) {
            Intent createGood = new Intent(mFragment.getContext(), NewPurchasesActivity.class);
            createGood.putExtra("GOOD_EDIT", false);
            createGood.putExtra("GOOD_ADD", false);
            createGood.putExtra("GOOD_ENTITY", new GoodsItemEntity());
            mFragment.requireContext().startActivity(createGood);
        } else {
            ACAdminDialogUtils.showACDialogForGoods(type, mFragment.getContext());
        }
    }

    public void getGoodsList(Map<String, Object> map) {
        DialogHelper.showProgressDialog(mFragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getGoodsList(map).enqueue(new Callback<BaseEntity<ListResponse<List<GoodsListEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<GoodsListEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<GoodsListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.getGoodsList(response.body().getData().getList());
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<GoodsListEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getRecommendList(Map<String, Object> map) {
        DialogHelper.showProgressDialog(mFragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getRecommendList(map).enqueue(new Callback<BaseEntity<ListResponse<List<RecommendListEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<RecommendListEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<RecommendListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.getRecommendList(response.body().getData().getList());
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<RecommendListEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 商品首页--自营商品
     *
     * @param map
     */
    public void getSelfSupportMaterialsList(Map<String, Object> map) {
        DialogHelper.showProgressDialog(mFragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getSelfSupportList(map).enqueue(new Callback<BaseEntity<ListResponse<List<RecommendListEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<RecommendListEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<RecommendListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.getRecommendList(response.body().getData().getList());
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<RecommendListEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 商品首页--促销商品
     *
     * @param map
     */
    public void getPromotionsList(Map<String, Object> map) {
        DialogHelper.showProgressDialog(mFragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getPromotionsList(map).enqueue(new Callback<BaseEntity<ListResponse<List<RecommendListEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<RecommendListEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<RecommendListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.getRecommendList(response.body().getData().getList());
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<RecommendListEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getPriceSort() {
        List<DictEntity3> list = new ArrayList<>();
        list.add(new DictEntity3("1", "从低到高"));
        list.add(new DictEntity3("2", "从高到低"));
        mFragment.showPriceSort(list);
    }

    public void getAreaChoose() {
        APIManager.getInstance().getGoodsAPI().getAreaChoose(mRepertory.getAreaCode()).enqueue(new Callback<BaseEntity<List<AreaChooseEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<AreaChooseEntity>>> call, @NotNull Response<BaseEntity<List<AreaChooseEntity>>> response) {
                if (response.body() == null) {
                    return;
                }
                if ("ok".equals(response.body().getState())) {
                    mFragment.getAreaChoose(response.body().getData());
                } else {
                    MToast.showToast(mFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<AreaChooseEntity>>> call, @NotNull Throwable t) {
            }
        });
    }

    public void getConcreteList(Map<String, Object> map) {
        DialogHelper.showProgressDialog(mFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getConcreteList(map).enqueue(new Callback<BaseEntity<ListResponse<List<ConcreteEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<ConcreteEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<ConcreteEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.getConcreteList(response.body().getData().getList());
                } else {
                    MToast.showToast(mFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<ConcreteEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mFragment.getActivity(), t.getMessage());
            }
        });
    }

    public String getAreaCode() {
        return mRepertory.getAreaCode();
    }

    public void getMenuModel(String id) {
        DialogHelper.showProgressDialog(mFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);

        Map map = new HashMap<String,Object>();
        if (map == null) {
            map = new HashMap(2);
        }
        map.put("industryId", id);
        map.put("areaCode", mRepertory.getAreaCode());
        APIManager.getInstance().getMaterialAPI().getItemCatList(map).enqueue(new Callback<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Response<BaseEntity<List<MenuEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFragment.showecommendCategoryData(response.body().getData());

                } else {
                    MToast.showToast(mFragment.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mFragment.getActivity(), t.getMessage());
            }
        });
    }

    public void getClassListeData(String id, boolean issecondClass) {


        NewAPIManager.getInstance().getGoodsAPI().findTwoOrThreeLevelData(getAreaCode(), id).enqueue(new Callback<BaseEntity<List<TwoOrThreeLevelEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<TwoOrThreeLevelEntity>>> call, Response<BaseEntity<List<TwoOrThreeLevelEntity>>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if(issecondClass){
                        MenuEntity<MenuEntity<MenuEntity>> arrlist = new MenuEntity<>();
                        List<MenuEntity<MenuEntity>> list  = new ArrayList<>();
                        for (TwoOrThreeLevelEntity datum : response.body().getData()) {
                            MenuEntity data = new MenuEntity();
                            data.setId(datum.getId());
                            data.setName(datum.getName());
                            list.add(data);
                        }
                        arrlist.setDatas(list);
                        mFragment.setMatterChooseMaterialType(arrlist);
                    }else{
                        MenuEntity<MenuEntity> threelist = new MenuEntity<>();
                        List<MenuEntity> list  = new ArrayList<>();
                        for (TwoOrThreeLevelEntity datum : response.body().getData()) {
                            MenuEntity data = new MenuEntity();
                            data.setId(datum.getId());
                            data.setName(datum.getName());
                            list.add(data);
                        }
                        threelist.setDatas(list);
                        mFragment.setMatterChooseMaterialName(threelist);
                    }
                } else {
                    MToast.showToast(mFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<TwoOrThreeLevelEntity>>> call, Throwable t) {
            }
        });

    }

    //获取跳转页需要传的数据
    public void recommendMenu(int position, boolean isMap) {
        APIManager.getInstance().getMaterialAPI().recommendMenuNew().enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                mFragment.showImageButtonData(data.getData(), position, isMap);
            }
        });
    }

    public void recomandCate(boolean isRefresh) {
        Type type = new TypeToken<List<HomeMenuEntity>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU, type);
        List<HomeMenuEntity> data = new ArrayList<>();
        if (null != obj && isRefresh == false) {
            List<HomeMenuEntity> dataList = (List<HomeMenuEntity>) obj;
            data.addAll(dataList);
            mFragment.showRecommendCate(data, isRefresh);
        }
        if (data.size() == 0 || isRefresh) {
            getTuijianData(isRefresh);
        }
    }


    /**
     * 获取大首页推荐数据
     *
     * @param isRefresh
     */
    private void getTuijianData(boolean isRefresh) {
        APIManager.getInstance().getBigHomeAPI().getAllRecomandCate().enqueue(new ICallBack<BaseEntity<List<HomeMenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<HomeMenuEntity>> data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                    if (data.getData() != null && data.getData().size() > 0) {
                        String cacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU);
                        if (!mHashNet.equals(cacheOperationHash)) {
                            mFragment.showRecommendCate(data.getData(), false);
                            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU, data.getData());
                        } else {
                            mFragment.showRecommendCate(data.getData(), isRefresh);
                        }
                    }
                } else {
                    MToast.showToast(mFragment.getActivity(), data.getMsg());
                }
            }
        });
    }
}
